import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/models/topic_detail_model.dart';
import 'package:live_music/pages/topic/widget/list_card_topic.dart';
import 'package:live_music/services/topicService.dart';

// ignore: must_be_immutable
class TopicMimeWidget extends StatefulWidget {
  final int type;
  Function onRefresh;
  TopicMimeWidget({Key key, this.type}) : super(key: key);
  @override
  _TopicMimeWidgetState createState() => _TopicMimeWidgetState();
}

class _TopicMimeWidgetState extends State<TopicMimeWidget>
    with AutomaticKeepAliveClientMixin {
  // 下拉刷新控制器
  EasyRefreshController _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  // 列表数组模型
  List<TopicDetailModel> _topicListModel;
  int pageNo = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg;
  String keyWord = "";
  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    widget.onRefresh = _onRefresh;
    getData();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  getData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {
        "pageNo": pageNo,
        "pageSize": pageSize,
      };
      Map<String, dynamic> result = await TopicService.queryUserTopic(data);
      List<dynamic> topicList = result['body'];
      TopicListModel topicListModel = TopicListModel.fromJson(topicList);
      setState(() {
        pageNo++;
        hasMore = pageSize == topicListModel.list.length;
        if (replace) {
          _topicListModel = topicListModel.list;
        } else {
          _topicListModel.addAll(topicListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    setState(() {
      pageNo = 1;
    });
    await getData(replace: true);
    if (error) {
      setState(() => error = false);
    }
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await getData(replace: false);
    }
    // // 结束加载
    _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
        emptyWidget: PageFeedBack(
          loading: loading,
          error: error,
          empty: _topicListModel.isEmpty,
          errorMsg: errorMsg,
          onErrorTap: () => _easyRefreshController.callRefresh(),
          onEmptyTap: () => _easyRefreshController.callRefresh(),
        ).build(),
        header: null,
        footer: ClassicalFooter(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        topBouncing: false,
        onRefresh: null,
        onLoad: _topicListModel.isEmpty ? null : _onLoad,
        child: GridView.count(
            padding: const EdgeInsets.all(4),
            mainAxisSpacing: 4,
            crossAxisSpacing: 4,
            crossAxisCount: 2,
            childAspectRatio: 0.9,
            children: _topicListModel.map((item) {
              return ListCardTopic(topicItem: item);
            }).toList()));
  }

  @override
  bool get wantKeepAlive => true;
}
